#!/bin/sh
# shellcheck shell=dash disable=SC2169,SC3010,SC3014

# we exit if if-down.d is called for "lo"
if [[ "${IFACE}" == "lo" ]]; then
  exit 0
fi

echo -n "${IFACE}: "

# make sure all network filesystems are unmounted before shutting down
# the network
/bin/umount -a -f -t nfs,cifs

# check if we have to stop wpa supplicant in case this
# is a wlan connection to be stopped
case ${IFACE} in
  wlan*)
    # stop WPA Supplicant if this is a WiFi connection
    killall -q wpa_supplicant

    # make sure that the wifi power is disabled
    /usr/sbin/rfkill block wlan
  ;;
esac

# make sure to bring down the interface
/sbin/ip link set dev "${IFACE}" down

# if a link down has been identified we remove the hasLink
# status file
if [[ "$(cat "/sys/class/net/${IFACE}/carrier" 2>/dev/null)" != "1" ]]; then
  echo -n "link down, "
  rm -f /var/status/hasLink
  rm -f /var/status/hasInternet
fi

# if the interface lost its IP we remove hasIP
IP=$(ip -4 addr show dev "${IFACE}" | sed -En -e 's/.*inet ([0-9.]+).*/\1/p')
if [[ -z "${IP}" ]]; then
  echo -n "no ip, "
  rm -f /var/status/hasIP
  rm -f /var/status/hasInternet
fi

exit 0
